import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { HttpClient, HttpRequest, HttpProgressEvent } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';

@Injectable({
	providedIn: 'root',
})
export class SettingsService implements Resolve<Settings> {
	public licenseInfo$: BehaviorSubject<any>;
	constructor(protected http: HttpClient) {
		this.licenseInfo$ = new BehaviorSubject({});
	}
	private _licenseInfo;

	get licenseInfo() {
		return this._licenseInfo;
	}

	get() {
		return this.http.get<Settings>('/api/profile').toPromise();
	}

	patch(body: any) {
		return this.http.patch('/api/admin/profile', body).toPromise();
	}

	async resolve(route: ActivatedRouteSnapshot) {
		return this.get();
	}

	licUpload(payload: FormData) {
		const req = new HttpRequest('POST', '/api/admin/license', payload, { reportProgress: true });
		return this.http.request<HttpProgressEvent>(req).pipe(map((event: HttpProgressEvent) => event));
	}

	updateLicenseInfo(data) {
		if(!!data){
			const licenseInfo = {
				expired: data.profile.expired_at === 0 ? false : new Date(data.profile.expired_at*1000) < new Date(),
				expiredAt: data.profile.expired_at,
				companyName: data.profile.company_name,
				showAlert: data.showAlert
			}
			this._licenseInfo = licenseInfo;
			this.licenseInfo$.next(licenseInfo);
		}
	}

	async fetchLicenseInfo() {
		const profile = await this.get();
		if (new Date(profile.expired_at*1000) < new Date()) {
			this.updateLicenseInfo({profile});
		}
	}
}

export interface Settings {
	admin_total: number;
	launched_at: number;
	upgraded_at: number;
	expires_at: number;

	name: string;
	version: string;
	logo: string;
	favicon: string;
	grantee: string;
	picture_space_usage: string;
	expired_at: number;
	company_name: string;
}

export interface LicenseInfo {
	expired: boolean;
	expiredAt: number;
	companyName: string;
}